#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
/**
9 * @Title: MD5Util.java
 * @Package: com.cloudscope.bioyong.util
 * @Author: 李季
 * @Date: 2016年1月28日
 * @Time: 下午3:53:25
 * @Copyright: 云科凯创@2016
 */
package ${package}.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Description: MD5Util
 *
 * @author 李季
 * @date 2019/8/6 15:28
 *
 * <pre>
 *              ${copyright}
 *      Copyright (c) 2019. All Rights Reserved.
 * </pre>
 */
@Slf4j
public class MD5Util {

	private static final int COMMON_BYTE_RW_LENGTH = 1024;
	private MD5Util() {
		// make constructor private
	}
	/**
	 * Description:
	 * <生成文件的MD5码>
	 * @author 李季
	 * @date 15:36 2019/8/8
	 * @param file 1
	 * @return java.lang.String
	 **/
	public static String getFileMD5(File file) {
		// 如果不是文件
	    if (!file.isFile()){
	    	return null;
	    }
	    MessageDigest digest;
	    byte[] buffer = new byte[1024];
	    int len;
	    try (FileInputStream in = new FileInputStream(file)){
	    	digest = MessageDigest.getInstance("MD5");
	        while ((len = in.read(buffer, 0, COMMON_BYTE_RW_LENGTH)) != -1) {
	        	digest.update(buffer, 0, len);
	        }
	    } catch (Exception e) {
	      log.error("get file [{}] md5 error", file.getAbsolutePath(), e);
	      return null;
	    }
	    BigInteger bigInt = new BigInteger(1, digest.digest());
	    return bigInt.toString(16);
	}
	/**
	 * Description:
	 * <生成字符串的MD5码>
	 * @author 李季
	 * @date 15:36 2019/8/8
	 * @param str 1
	 * @return java.lang.String
	 **/
	public static String getStringMD5(String str) {
		// 如果为空
	    if(null == str){
			return null;
		}
	    MessageDigest digest;
    	try {
			digest = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			log.error("no such algorithm", e);
			return null;
		}
		digest.update(str.getBytes(StandardCharsets.UTF_8));
		byte[] b = digest.digest();

		int i;

		StringBuilder buf = new StringBuilder();
		for (int offset = 0; offset < b.length; offset++) {
			i = b[offset];
			if (i < 0){
				i += 256;
			}
			if (i < 16) {
				buf.append("0");
			}
			buf.append(Integer.toHexString(i));
		}

	    return buf.toString();
	}

	/**
	 * Description:
	 * <生成byte数组的md5>
	 * @author wenxiaopeng
	 * @date 15:36 2020/03/03
	 * @param in 1
	 * @return java.lang.String
	 **/
	public static String getByteMD5(byte[] in) {
		try {
			MessageDigest digest = MessageDigest.getInstance("MD5");
			digest.update(in);
			BigInteger bigInt = new BigInteger(1, digest.digest());
			return bigInt.toString(16);
		} catch (Exception e) {
			log.error("error info ",e);
			return null;
		}
	}

}
